package com.example.backend.controller;

import com.example.backend.domain.enums.TicketStatus;
import com.example.backend.dto.ApiResponse;
import com.example.backend.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 工单工作流增强控制器
 * 提供状态机验证、优先级管理、分类树、SLA跟踪、自动分配等功能
 */
@Tag(name = "工单工作流管理", description = "工单工作流增强功能接口")
@RestController
@RequestMapping("/api/ticket-workflow")
public class TicketWorkflowController {

    @Autowired
    private TicketStateMachineService stateMachineService;

    @Autowired
    private TicketPriorityManagementService priorityService;

    @Autowired
    private TicketCategoryTreeService categoryTreeService;

    @Autowired
    private TicketSLATrackingService slaTrackingService;

    @Autowired
    private TicketAutoAssignmentService autoAssignmentService;

    // ==================== 状态机验证 ====================

    @Operation(summary = "验证状态转换", description = "验证工单状态转换是否合法")
    @GetMapping("/state-machine/validate")
    public ResponseEntity<ApiResponse<Boolean>> validateStateTransition(
            @Parameter(description = "当前状态") @RequestParam TicketStatus currentStatus,
            @Parameter(description = "目标状态") @RequestParam TicketStatus targetStatus) {
        
        boolean isValid = stateMachineService.isValidTransition(currentStatus, targetStatus);
        String message = isValid ? "状态转换合法" : "状态转换不合法";
        
        return ResponseEntity.ok(ApiResponse.success(message, isValid));
    }

    @Operation(summary = "获取允许的状态转换", description = "获取当前状态允许转换到的状态列表")
    @GetMapping("/state-machine/allowed-transitions")
    public ResponseEntity<ApiResponse<List<TicketStatus>>> getAllowedTransitions(
            @Parameter(description = "当前状态") @RequestParam TicketStatus currentStatus) {
        
        List<TicketStatus> allowedTransitions = stateMachineService.getAllowedTransitions(currentStatus)
                .stream().toList();
        
        return ResponseEntity.ok(ApiResponse.success("获取允许的状态转换成功", allowedTransitions));
    }

    @Operation(summary = "获取状态转换描述", description = "获取状态转换的业务描述")
    @GetMapping("/state-machine/transition-description")
    public ResponseEntity<ApiResponse<String>> getTransitionDescription(
            @Parameter(description = "当前状态") @RequestParam TicketStatus currentStatus,
            @Parameter(description = "目标状态") @RequestParam TicketStatus targetStatus) {
        
        String description = stateMachineService.getTransitionDescription(currentStatus, targetStatus);
        return ResponseEntity.ok(ApiResponse.success("获取状态转换描述成功", description));
    }

    @Operation(summary = "获取业务规则说明", description = "获取工单状态转换的业务规则说明")
    @GetMapping("/state-machine/business-rules")
    public ResponseEntity<ApiResponse<String>> getBusinessRules() {
        String rules = stateMachineService.getBusinessRulesDescription();
        return ResponseEntity.ok(ApiResponse.success("获取业务规则成功", rules));
    }

    // ==================== 优先级管理 ====================

    @Operation(summary = "获取优先级配置", description = "获取所有优先级的配置信息")
    @GetMapping("/priority/configs")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getPriorityConfigs() {
        Map<String, Object> configs = priorityService.getAllPriorityConfigs()
                .entrySet().stream()
                .collect(java.util.stream.Collectors.toMap(
                    entry -> entry.getKey().name(),
                    entry -> Map.of(
                        "displayName", entry.getValue().getDisplayName(),
                        "color", entry.getValue().getColor(),
                        "weight", entry.getValue().getWeight(),
                        "responseTimeSLA", entry.getValue().getResponseTimeSLA().toHours() + "小时",
                        "resolutionTimeSLA", entry.getValue().getResolutionTimeSLA().toHours() + "小时"
                    )
                ));
        
        return ResponseEntity.ok(ApiResponse.success("获取优先级配置成功", configs));
    }

    @Operation(summary = "建议优先级", description = "根据工单内容建议优先级")
    @PostMapping("/priority/suggest")
    public ResponseEntity<ApiResponse<String>> suggestPriority(
            @Parameter(description = "工单标题") @RequestParam String title,
            @Parameter(description = "工单描述") @RequestParam String description) {
        
        var suggestedPriority = priorityService.suggestPriorityByContent(title, description);
        String priorityName = priorityService.getPriorityDisplayName(suggestedPriority);
        
        return ResponseEntity.ok(ApiResponse.success("优先级建议", priorityName));
    }

    @Operation(summary = "计算SLA时间", description = "计算工单的SLA截止时间")
    @GetMapping("/priority/calculate-sla")
    public ResponseEntity<ApiResponse<Map<String, Object>>> calculateSLA(
            @Parameter(description = "优先级") @RequestParam String priority,
            @Parameter(description = "创建时间") @RequestParam String createdAt) {
        
        try {
            var ticketPriority = com.example.backend.domain.enums.TicketPriority.valueOf(priority.toUpperCase());
            var createdTime = java.time.Instant.parse(createdAt);
            
            var responseSLA = priorityService.calculateResponseSLA(ticketPriority, createdTime);
            var resolutionSLA = priorityService.calculateResolutionSLA(ticketPriority, createdTime);
            
            Map<String, Object> slaInfo = Map.of(
                "priority", priorityService.getPriorityDisplayName(ticketPriority),
                "responseSLA", responseSLA.toString(),
                "resolutionSLA", resolutionSLA.toString(),
                "responseSLAHours", priorityService.getPriorityConfig(ticketPriority).getResponseTimeSLA().toHours(),
                "resolutionSLAHours", priorityService.getPriorityConfig(ticketPriority).getResolutionTimeSLA().toHours()
            );
            
            return ResponseEntity.ok(ApiResponse.success("计算SLA时间成功", slaInfo));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("计算SLA时间失败: " + e.getMessage()));
        }
    }

    // ==================== 分类树管理 ====================

    @Operation(summary = "获取分类树", description = "获取完整的工单分类树结构")
    @GetMapping("/category/tree")
    public ResponseEntity<ApiResponse<List<TicketCategoryTreeService.CategoryTreeNode>>> getCategoryTree() {
        List<TicketCategoryTreeService.CategoryTreeNode> tree = categoryTreeService.buildActiveCategoryTree();
        return ResponseEntity.ok(ApiResponse.success("获取分类树成功", tree));
    }

    @Operation(summary = "获取分类完整路径", description = "获取指定分类的完整路径")
    @GetMapping("/category/path/{categoryId}")
    public ResponseEntity<ApiResponse<String>> getCategoryPath(
            @Parameter(description = "分类ID") @PathVariable Long categoryId) {
        
        String path = categoryTreeService.getCategoryFullPath(categoryId);
        return ResponseEntity.ok(ApiResponse.success("获取分类路径成功", path));
    }

    @Operation(summary = "获取子分类", description = "获取指定分类的所有子分类ID")
    @GetMapping("/category/subcategories/{categoryId}")
    public ResponseEntity<ApiResponse<List<Long>>> getSubCategories(
            @Parameter(description = "分类ID") @PathVariable Long categoryId) {
        
        List<Long> subCategoryIds = categoryTreeService.getAllSubCategoryIds(categoryId);
        return ResponseEntity.ok(ApiResponse.success("获取子分类成功", subCategoryIds));
    }

    @Operation(summary = "搜索分类", description = "根据关键词搜索分类")
    @GetMapping("/category/search")
    public ResponseEntity<ApiResponse<List<TicketCategoryTreeService.CategoryTreeNode>>> searchCategories(
            @Parameter(description = "搜索关键词") @RequestParam(required = false) String keyword) {
        
        List<TicketCategoryTreeService.CategoryTreeNode> results = categoryTreeService.searchCategories(keyword);
        return ResponseEntity.ok(ApiResponse.success("搜索分类成功", results));
    }

    @Operation(summary = "获取分类统计", description = "获取分类的统计信息")
    @GetMapping("/category/statistics")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getCategoryStatistics() {
        Map<String, Object> statistics = categoryTreeService.getCategoryStatistics();
        return ResponseEntity.ok(ApiResponse.success("获取分类统计成功", statistics));
    }

    // ==================== SLA跟踪 ====================

    @Operation(summary = "获取SLA跟踪结果", description = "获取工单的SLA跟踪结果")
    @GetMapping("/sla/tracking/{ticketId}")
    public ResponseEntity<ApiResponse<TicketSLATrackingService.SLATrackingResult>> getSLATracking(
            @Parameter(description = "工单ID") @PathVariable Long ticketId) {
        
        // 这里需要根据ticketId获取Ticket对象，暂时返回模拟数据
        // 实际使用时需要注入TicketService
        return ResponseEntity.ok(ApiResponse.success("获取SLA跟踪结果成功", null));
    }

    @Operation(summary = "获取违反SLA的工单", description = "获取违反SLA的工单列表")
    @GetMapping("/sla/violated")
    public ResponseEntity<ApiResponse<List<Long>>> getViolatedSLATickets() {
        List<Long> violatedTickets = slaTrackingService.getViolatedSLATickets();
        return ResponseEntity.ok(ApiResponse.success("获取违反SLA的工单成功", violatedTickets));
    }

    @Operation(summary = "获取SLA警告工单", description = "获取即将违反SLA的工单列表")
    @GetMapping("/sla/warning")
    public ResponseEntity<ApiResponse<List<Long>>> getWarningSLATickets(
            @Parameter(description = "警告小时数") @RequestParam(defaultValue = "2") int warningHours) {
        
        List<Long> warningTickets = slaTrackingService.getWarningSLATickets(warningHours);
        return ResponseEntity.ok(ApiResponse.success("获取SLA警告工单成功", warningTickets));
    }

    @Operation(summary = "获取SLA统计", description = "获取SLA统计信息")
    @GetMapping("/sla/statistics")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getSLAStatistics() {
        Map<String, Object> statistics = slaTrackingService.getSLAStatistics();
        return ResponseEntity.ok(ApiResponse.success("获取SLA统计成功", statistics));
    }

    // ==================== 自动分配 ====================

    @Operation(summary = "自动分配工单", description = "根据规则自动分配工单")
    @PostMapping("/assignment/auto-assign/{ticketId}")
    public ResponseEntity<ApiResponse<TicketAutoAssignmentService.AssignmentResult>> autoAssignTicket(
            @Parameter(description = "工单ID") @PathVariable Long ticketId) {
        
        // 这里需要根据ticketId获取Ticket对象
        // 实际使用时需要注入TicketService
        return ResponseEntity.ok(ApiResponse.success("自动分配工单成功", null));
    }

    @Operation(summary = "获取分配建议", description = "获取工单的分配建议")
    @GetMapping("/assignment/suggestions/{ticketId}")
    public ResponseEntity<ApiResponse<List<TicketAutoAssignmentService.AssignmentResult>>> getAssignmentSuggestions(
            @Parameter(description = "工单ID") @PathVariable Long ticketId) {
        
        // 这里需要根据ticketId获取Ticket对象
        // 实际使用时需要注入TicketService
        return ResponseEntity.ok(ApiResponse.success("获取分配建议成功", null));
    }

    @Operation(summary = "检查是否可以自动分配", description = "检查工单是否可以自动分配")
    @GetMapping("/assignment/can-auto-assign/{ticketId}")
    public ResponseEntity<ApiResponse<Boolean>> canAutoAssign(
            @Parameter(description = "工单ID") @PathVariable Long ticketId) {
        
        // 这里需要根据ticketId获取Ticket对象
        // 实际使用时需要注入TicketService
        return ResponseEntity.ok(ApiResponse.success("检查自动分配状态成功", false));
    }

    @Operation(summary = "获取分配规则", description = "获取所有分配规则")
    @GetMapping("/assignment/rules")
    public ResponseEntity<ApiResponse<List<TicketAutoAssignmentService.AssignmentRule>>> getAssignmentRules() {
        List<TicketAutoAssignmentService.AssignmentRule> rules = autoAssignmentService.getAssignmentRules();
        return ResponseEntity.ok(ApiResponse.success("获取分配规则成功", rules));
    }

    @Operation(summary = "更新分配规则", description = "更新分配规则的启用状态")
    @PutMapping("/assignment/rules/{ruleName}")
    public ResponseEntity<ApiResponse<Void>> updateAssignmentRule(
            @Parameter(description = "规则名称") @PathVariable String ruleName,
            @Parameter(description = "是否启用") @RequestParam boolean enabled) {
        
        autoAssignmentService.updateAssignmentRule(ruleName, enabled);
        return ResponseEntity.ok(ApiResponse.success("更新分配规则成功", null));
    }

    // ==================== 工作流综合功能 ====================

    @Operation(summary = "获取工作流概览", description = "获取工单工作流的概览信息")
    @GetMapping("/overview")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getWorkflowOverview() {
        Map<String, Object> overview = Map.of(
            "stateMachineRules", stateMachineService.getBusinessRulesDescription(),
            "priorityConfigs", priorityService.getAllPriorityConfigs().size(),
            "categoryStatistics", categoryTreeService.getCategoryStatistics(),
            "slaStatistics", slaTrackingService.getSLAStatistics(),
            "assignmentRules", autoAssignmentService.getAssignmentRules().size()
        );
        
        return ResponseEntity.ok(ApiResponse.success("获取工作流概览成功", overview));
    }
}
